using System.Collections.Generic;
using System.Threading;

namespace OracleInternal.Common
{
	internal class SQLParseInfoPool
	{
		private class SQLParseInfo
		{
			internal bool hasRowId;

			internal string sqlWithRowId;

			internal long m_lastUsedCount;
		}

		private object m_sync = new object();

		private long m_LastUsedCount;

		private Dictionary<string, SQLParseInfo> m_cache;

		internal int m_maxCacheSize;

		internal SQLParseInfoPool(int maxCacheSize)
		{
			m_maxCacheSize = maxCacheSize;
			m_cache = new Dictionary<string, SQLParseInfo>(m_maxCacheSize);
		}

		private void RemoveLRU()
		{
			string text = null;
			long num = long.MaxValue;
			foreach (KeyValuePair<string, SQLParseInfo> item in m_cache)
			{
				if (item.Value.m_lastUsedCount < num)
				{
					num = item.Value.m_lastUsedCount;
					text = item.Key;
				}
			}
			if (text != null)
			{
				m_cache.Remove(text);
			}
		}

		internal void Put(string cmdText, string cmdTextWithRowId, bool hadRowId)
		{
			if (m_cache.ContainsKey(cmdText))
			{
				return;
			}
			lock (m_sync)
			{
				if (!m_cache.ContainsKey(cmdText))
				{
					if (m_cache.Count >= m_maxCacheSize)
					{
						RemoveLRU();
					}
					m_cache.Add(cmdText, new SQLParseInfo
					{
						hasRowId = hadRowId,
						sqlWithRowId = cmdTextWithRowId,
						m_lastUsedCount = ++m_LastUsedCount
					});
				}
			}
		}

		internal string Get(string cmdText, out bool hadRowId)
		{
			hadRowId = false;
			SQLParseInfo value = null;
			try
			{
				if (m_cache.TryGetValue(cmdText, out value))
				{
					value.m_lastUsedCount = Interlocked.Increment(ref m_LastUsedCount);
					hadRowId = value.hasRowId;
					return value.sqlWithRowId;
				}
				return null;
			}
			catch
			{
				return null;
			}
		}
	}
}
